package org.beans.expense.common.service;

import org.beans.expense.common.domain.DailyExpense;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * @author: arunachalam
 * @since: 2/11/13
 */
@Repository
@Transactional
@Named
public class DailyExpenseService implements IDailyExpenseService
{
    private static Logger logger = LoggerFactory.getLogger(DailyExpenseService.class);
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void create(DailyExpense expense)
    {
        logger.info("creating a {} ", expense);
        entityManager.persist(expense);
    }

    @Override
    public DailyExpense findById(long id)
    {
        logger.info("Finding by id {} ", id);
        return entityManager.find(DailyExpense.class, id);
    }

    @Override
    public List<DailyExpense> findAll()
    {
        Query query = entityManager.createQuery("select a from DailyExpense a order by createdDateTime desc");
        query.setFirstResult(0);
        query.setMaxResults(Integer.MAX_VALUE);
        return query.getResultList();
    }

    @Override
    public long countAll()
    {
        Query query = entityManager.createQuery("select count(a) from DailyExpense a");
        query.setFirstResult(0);
        query.setMaxResults(Integer.MAX_VALUE);
        return (Long) query.getSingleResult();
    }

    @Override
    public void update(DailyExpense expense)
    {
        logger.info("Updating a entry {} ", expense);
        entityManager.merge(expense);
    }

    @Override
    public void delete(DailyExpense expense)
    {
        logger.info("Deleting a entry {} ", expense);
        entityManager.remove(findById(expense.getId()));
    }

    @Override
    public void deleteAll()
    {
        Query query = entityManager.createQuery("delete from DailyExpense");
        query.executeUpdate();
    }
}
